package com.hdu.dwh.exception;


import com.hdu.dwh.enums.HttpStatusEnum;
import com.hdu.dwh.results.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.RestClientException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.stream.Collectors;


@RestControllerAdvice  //控制器增强类
@Slf4j
public class ExceptionCatch {

    /**
     * 处理不可控异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception e){
        e.printStackTrace();
        log.error("catch exception:{}",e.getMessage());
        return ResponseResult.fail(HttpStatusEnum.ERROR.getCode(), e.getMessage());
    }

    /**
     * 处理可控异常  自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult<?> exception(CustomException e){
        log.error("catch exception:{}",e);
        return ResponseResult.fail(e.getHttpStatusEnum());
    }

    /**
     * 处理RestClient异常，一般用于Web请求
     * @param e
     * @return
     */
    @ExceptionHandler(FlinkWebException.class)
    @ResponseBody
    public ResponseResult exception(FlinkWebException e){
        log.error("catch FlinkWebException:{}", e.getMessage());
        return ResponseResult.fail(HttpStatusEnum.FLINK_ERROR.getCode(), e.getMessage(), e.getFlinkMessage());
    }

    /**
     * 处理notnull异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handleValidException(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining("; "));
        return ResponseResult.fail(msg);
    }


    /**
     * knife4j图标未找到 异常忽略
     * @param ex
     * @param request
     * @return
     */
    @ExceptionHandler(NoResourceFoundException.class)
    public ResponseEntity<String> handleNoResourceFound(NoResourceFoundException ex, HttpServletRequest request) {
        if (request.getRequestURI().equals("/favicon.ico")) {
            return ResponseEntity.ok().build(); // 忽略
        }
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("资源未找到");
    }
}
